﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using centraldba_library.Data;

namespace centraldba_library.Admin
{
    public class msx_server : INotifyPropertyChanged
    {
        private string _server_name, _database_name, _connectionStringTemplate;
        private ObservableCollection<target_group> _msx_groups;
        private ObservableCollection<target_server> _all_servers;
        private SortedDictionary<string, string> _config_settings;

        #region " Constructor "

        public msx_server(string connectionStringTemplate, string serverName, string databaseName)
        {
            bool validString = true;

            if (!connectionStringTemplate.Contains("Data Source=yourserver"))
                validString = false;

            if (!connectionStringTemplate.Contains("Initial Catalog=centraldba_db"))
                validString = false;

            if (validString)
            {
                // Initialize properties
                _connectionStringTemplate = connectionStringTemplate;
                NotifyPropertyChanged("connection_string");
                NotifyPropertyChanged("connection_string_masterdb");

                server_name = serverName;
                database_name = databaseName;
                _all_servers = null;
                _msx_groups = null;
                _config_settings = null;

                // Get the data
                RefreshServers();
                RefreshMSXGroups();
                RefreshConfig();
            }
            else
            {
                throw new Exception("The setting centraldba_db_template has been tampered with.  Please do not change [Data Source=yourserver] or [Initial Catalog=centraldba_db].");
            }
        }

        #endregion

        #region " Events "

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }

        #endregion

        #region " Properties "

        public string server_name
        {
            get { return _server_name; }
            set
            {
                if (!value.Equals(_server_name))
                {
                    _server_name = value;
                    NotifyPropertyChanged("server_name");
                }
            }
        }

        public string database_name
        {
            get { return _database_name; }
            set
            {
                if (!value.Equals(_database_name))
                {
                    _database_name = value;
                    NotifyPropertyChanged("database_name");
                }
            }
        }

        public string connection_string
        {
            get
            {
                string value = _connectionStringTemplate.Replace("Data Source=yourserver", "Data Source=" + _server_name);
                value = value.Replace("Initial Catalog=centraldba_db", "Initial Catalog=" + _database_name);

                return value;
            }
        }

        public string connection_string_masterdb
        {
            get
            {
                string value = _connectionStringTemplate.Replace("Data Source=yourserver", "Data Source=" + _server_name);
                value = value.Replace("Initial Catalog=centraldba_db", "Initial Catalog=master");

                return value;
            }
        }

        public ObservableCollection<target_group> msx_groups
        {
            get { return _msx_groups; }
        }

        public ObservableCollection<target_server> all_servers
        {
            get { return _all_servers; }
        }

        public SortedDictionary<string, string> config_settings
        {
            get { return _config_settings; }
        }

        #endregion

        #region " Methods "

        private void RefreshMSXGroups()
        {
            // Declare Local Variables
            ObservableCollection<target_group> new_groups = new ObservableCollection<target_group>();
            SqlCommand cm = null;
            SqlDataReader dr = null;
            target_group group;

            try
            {
                // Get the data
                cm = SqlHelper.GetCommand(connection_string, "[dbo].[spMSX_msx_groups]", CommandType.StoredProcedure);
                dr = cm.ExecuteReader();

                // Build the new group list
                while (dr.Read())
                {
                    group = new target_group(this);
                    if (dr.GetValue(0).ToString().Equals(string.Empty))
                        group.server_group_id = 0;
                    else
                        group.server_group_id = dr.GetInt32(0);
                    group.group_name = dr.GetString(1);
                    new_groups.Add(group);
                    group = null;
                }

                // Replace the group list
                if (_msx_groups != null)
                    _msx_groups.Clear();
                _msx_groups = new_groups;
            }
            catch (Exception ex) { }
            finally
            {
                // Release Objects
                SqlHelper.CloseConnection(cm, dr);
            }

            // Notify of the Updated Groups
            NotifyPropertyChanged("msx_groups");
        }

        private void RefreshServers()
        {
            // Declare Local Variables
            ObservableCollection<target_server> new_servers = new ObservableCollection<target_server>();
            SqlCommand cm = null;
            SqlDataReader dr = null;
            target_server server;

            try
            {
                // Get the data
                cm = SqlHelper.GetCommand(connection_string, "[dbo].[spMSX_msx_group_servermembers]", CommandType.StoredProcedure);
                dr = cm.ExecuteReader();

                // Build the new server list
                while (dr.Read())
                {
                    server = new target_server();
                    if (dr.GetValue(0).ToString().Equals(string.Empty))
                        server.server_group_id = 0;
                    else
                        server.server_group_id = dr.GetInt32(0);
                    server.server_id = dr.GetInt32(1);
                    server.server_name = dr.GetString(2);
                    server.enlist_date = dr.GetDateTime(3);
                    server.last_poll_date = dr.GetDateTime(4);
                    new_servers.Add(server);
                    server = null;
                }

                // Replace the server list
                if (_all_servers != null)
                    _all_servers.Clear();
                _all_servers = new_servers;
            }
            catch (Exception ex) { }
            finally
            {
                // Release Objects
                SqlHelper.CloseConnection(cm, dr);
            }

            // Notify of the Updated Servers
            NotifyPropertyChanged("all_servers");
        }

        private void RefreshConfig()
        {
            // Declare Local Variables
            SortedDictionary<string, string> new_config = new SortedDictionary<string, string>();
            SqlCommand cm = null;
            SqlDataReader dr = null;

            try
            {
                // Get the data
                cm = SqlHelper.GetCommand(connection_string, "SELECT cfg_key, cfg_value FROM [dbo].[tblMSX_configuration]", CommandType.Text);
                dr = cm.ExecuteReader();

                // Build the new server list
                while (dr.Read())
                {
                    new_config.Add(dr.GetString(0).Trim(), dr.GetString(1).Trim());
                }

                // Replace the server list
                if (_config_settings != null)
                    _config_settings.Clear();
                _config_settings = new_config;
            }
            catch (Exception ex) { }
            finally
            {
                // Release Objects
                SqlHelper.CloseConnection(cm, dr);
            }

            // Notify of the Updated Servers
            NotifyPropertyChanged("config_settings");
        }

        #endregion
    }
}
